搜索 K
Appearance
博客正在加载中...
Appearance
Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和静态页面物理分离,严格意义上说应该是动态请求跟静态请求分开。可以理解成使用 Nginx 处理静态页面,Tomcat 处理动态页面。
动静分离从目前实现角度来讲大致分为两种:
本文主要是实现第一种方式,需求:在服务器上准备 2 个文件夹,分别存放 HTML 文件和 images 文件,然后可以通过 Nginx 访问这些文件。 生活中的例子:就好比你去餐馆吃饭,Nginx 就相当于服务员,tomcat 就相当于厨师,你要一瓶饮料(相当于静态资源),服务员就能给你拿,而你说你要一盘鱼香肉丝(动态资源),那服务员只好给厨师讲,让他给你做,做完后服务员再返回给你。
准备静态资源:新建一个目录,然后新建 2 个文件夹:
mkdir /opt/staticFiles
cd /opt/staticFiles/
mkdir www
mkdir images
echo '<h1>static file<h1>' > www/static.html 图片的话请自行准备几个放到 images 文件夹里,例如这是我准备的:
ll /opt/staticFiles/images
总用量 1348
-rw-r--r--. 1 root root 68874 12月 16 01:07 1.jpg
-rw-r--r--. 1 root root 1308287 12月 16 04:53 2.jpg
修改 Nginx 配置文件,重点是添加 location:
location /www/ {
root /opt/staticFiles/;
}
location /images/ {
root /opt/staticFiles/;
autoindex on;
} 配置的作用:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream myserver {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 9001;
server_name localhost;
location /www/ {
root /opt/staticFiles/;
}
location /images/ {
root /opt/staticFiles/;
autoindex on;
}
location / {
proxy_pass http://myserver;
}
location ~ /edu/ {
proxy_pass http://127.0.0.1:8080;
}
location ~ /vod/ {
proxy_pass http://127.0.0.1:8081;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}分别访问 http://localhost:9001/images/ 和 http://localhost:9001/images/,效果如下: